﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;


namespace RaceList.activity.help
{
    /// <summary>
    ///     这里主要是封装了一些数据库中对Activity_Relay,Activity_SubRelay的操作
    /// </summary>
    public partial class RelayQuery
    {
        /// <summary>
        ///     只提供一个通过tagId查询的方法
        ///     一般不允许查询该表中的单个数据
        /// </summary>
        /// <param name="tagId"></param>
        /// <returns></returns>
        public static List<Activity_Relay_ZongChengji> GetActivity_ZongChengji(int cycleId)
        {
            ipowdb_suibian_webDataContext db = ConnHelper.ipowdb_suibian_web();
            Activity_Relay_Tag tag = db.Activity_Relay_Tag.Where(s => s.CycleId == cycleId).SingleOrDefault();
            if (tag != null)
                return tag.Activity_Relay_ZongChengji.ToList();
            return new List<Activity_Relay_ZongChengji>();
        }

        /// <summary>
        ///     添加总成绩Tag和Zongchengji
        /// </summary>
        /// <param name="cycleId"></param>
        public static void AddActivityZongChengji(int cycleId)
        {
            lock (new object())
            {
                Thread.Sleep(new Random().Next(1, 500));
                ipowdb_suibian_webDataContext db = ConnHelper.ipowdb_suibian_web();

                Activity_Relay_Tag tag = db.Activity_Relay_Tag.Where(s => s.CycleId == cycleId).SingleOrDefault();
                if (tag == null) //如果没有添加过数据的话
                {
                    tag = new Activity_Relay_Tag
                    {
                        AddTime = DateTime.Now,
                        CycleId = cycleId,
                    };
                    db.Activity_Relay_Tag.InsertOnSubmit(tag);
                    db.SubmitChanges();

                    List<Activity_Relay> list = GetPaihang(int.MaxValue); //先获取所有完成了比赛的集合

                    //对这些出现再排行榜的成绩需要对他们最后完成的成绩做一个判断
                    //必须是在截止日期之前完成的成绩才是有效的
                    list = list.Where(s => s.EditTime <= tag.Activity_Cycle.endDate).ToList();

                    int takeNum = list.Count > 10 ? 10 : list.Count; // 最多取前10名
                    list = list.Take(takeNum).ToList();

                    foreach (Activity_Relay item in list)
                    {
                        var zongChengji = new Activity_Relay_ZongChengji
                        {
                            TagId = tag.Id,
                            RelayId = item.Id,
                            AddTime = DateTime.Now,
                        };
                        db.Activity_Relay_ZongChengji.InsertOnSubmit(zongChengji);
                    }
                    db.SubmitChanges();

                    list = null;
                }
            }
        }
    }
}